package org.fastsyncer.server.jetty;

import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.log4j.PropertyConfigurator;
import org.fastsyncer.common.constant.CommonConstant;
import org.fastsyncer.common.exception.ConfigurationException;
import org.fastsyncer.common.util.ApplicationUtil;
import org.fastsyncer.common.util.PropertiesUtil;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.webapp.WebAppContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class JettyServer {

    private static final Logger logger = LoggerFactory.getLogger(JettyServer.class);

    private Server server;

    private WebAppContext ctx;

    private void loadLocal() throws ConfigurationException {
        // 这里会读取fastsyncer-server\target\classes路径下的编译生成文件,如果Project>>clean 那么文件会重新从src读取最新的配置
        URL proUrl = JettyServer.class.getClassLoader().getResource("application.properties");
        if (null == proUrl) {
            throw new ConfigurationException("Can not find file application.properties!");
        }
        String proPath = proUrl.getPath();
        Properties pro = PropertiesUtil.load(proPath);
        for (Entry<Object, Object> it : pro.entrySet()) {
            String key = (String) it.getKey();
            ApplicationUtil.setKey(key, (String) it.getValue());
        }
        // 保存配置文件地址
        ApplicationUtil.setKey(CommonConstant.CONFIG_PATH_APPLICATION_PROPERTIES, proPath);
        // /opt/eclipse/workspace/fastsyncer/fastsyncer-server
        String workspace = ApplicationUtil.getKey(CommonConstant.CONFIG_CURRENT_PATH);
        // /opt/eclipse/workspace/fastsyncer/fastsyncer-server/src/main/resources
        StringBuilder path = new StringBuilder(workspace).append(File.separator).append("src").append(File.separator).append("main").append(File.separator).append("resources");
        ApplicationUtil.setKey(CommonConstant.SERVER_ROOT, path.toString());
        // /opt/eclipse/workspace/fastsyncer/fastsyncer-server/src/main/resources/static/web.xml
        path.append(File.separator).append("static").append(File.separator).append("web.xml");
        ApplicationUtil.setKey(CommonConstant.SERVER_ROOT_DESCRIPTOR, path.toString());
        // 驱动地址：C:\\fastsyncer
        ApplicationUtil.setKey(CommonConstant.MANAGER_STORE_PATH, "C:\\fastsyncer");
        // 标记为当前启动方式开发模式
        ApplicationUtil.setKey(CommonConstant.CONFIG_IS_DEBUG, "true");
    }

    private void loadExt(String[] args) throws ConfigurationException {
        logger.info("args:" + Arrays.toString(args));
        // 绝对路径：/opt/fastsyncer-server
        String workspace = ApplicationUtil.getKey(CommonConstant.CONFIG_CURRENT_PATH);
        // 上下文：/opt/fastsyncer-server/ui
        StringBuilder path = new StringBuilder().append(workspace).append(File.separatorChar).append("ui");
        ApplicationUtil.setKey(CommonConstant.SERVER_ROOT, path.toString());
        // 描述文件：/opt/fastsyncer-server-X.X.X-Release/ui/static/web.xml
        path.append(File.separatorChar).append("static").append(File.separator).append("web.xml");
        ApplicationUtil.setKey(CommonConstant.SERVER_ROOT_DESCRIPTOR, path.toString());

        // 1.获取boot路径：/opt/fastsyncer-server/conf/boot/
        StringBuilder boot = new StringBuilder().append(workspace).append(File.separator).append("conf").append(File.separator).append("boot").append(File.separator);
        
        // /opt/fastsyncer-server/conf/boot/application.properties
        String appProp = boot + "application.properties";
        ApplicationUtil.setKey(CommonConstant.CONFIG_PATH_APPLICATION_PROPERTIES, appProp);
        Properties pro = PropertiesUtil.load(appProp);
        for (Entry<Object, Object> it : pro.entrySet()) {
            String key = (String) it.getKey();
            ApplicationUtil.setKey(key, (String) it.getValue());
        }
        // /opt/fastsyncer-server/conf/boot/log4j.properties
        String log4jProp = boot + "log4j.properties";
        if(new File(log4jProp).exists()){
            PropertyConfigurator.configure(log4jProp);
        }
        // 驱动地址：/opt/fastsyncer-server/conf
        ApplicationUtil.setKey(CommonConstant.MANAGER_STORE_PATH, new StringBuilder().append(workspace).append(File.separator).append("conf").toString());
    }

    private void start(String[] args) throws Exception {
        ApplicationUtil.setKey(CommonConstant.CONFIG_CURRENT_PATH, System.getProperty("user.dir"));
        if (args != null && args.length > 0) {
            loadExt(args);
        } else {
            loadLocal();
        }

        // 默认
        String _ip = ApplicationUtil.getKey(CommonConstant.SERVER_IP);
        String _port = ApplicationUtil.getKey(CommonConstant.SERVER_PORT);
        String _context = ApplicationUtil.getKey(CommonConstant.SERVER_CONTEXT);
        String _root = ApplicationUtil.getKey(CommonConstant.SERVER_ROOT);
        String _root_desc = ApplicationUtil.getKey(CommonConstant.SERVER_ROOT_DESCRIPTOR);
        // 服务地址
        String serviceAddress = new StringBuilder().append("http://").append(_ip).append(":").append(_port).append(_context).toString();
        ApplicationUtil.setKey(CommonConstant.SERVER_SERVICE_ADDRESS, serviceAddress);
        String auth = _context.endsWith("/") ? "authenticate" : "/authenticate";
        ApplicationUtil.setKey(CommonConstant.SERVER_SERVICE_ADDRESS_AUTHENTICATE, serviceAddress + auth);
        logger.info("ip:" + _ip);
        logger.info("port:" + _port);
        logger.info("context:" + _context);
        logger.info("root:" + _root);
        logger.info("root.descriptor:" + _root_desc);
        logger.info("service.address:" + serviceAddress);

        // 1.创建服务端口
        server = new Server(Integer.valueOf(_port));
        // 2.加载上下文
        ctx = new WebAppContext();
        // 设置上下文路径
        ctx.setContextPath(_context);
        // 设置Web内容上下文路径
        ctx.setResourceBase(_root);
        // 设置描述符位置
        ctx.setDescriptor(_root_desc);
        server.setHandler(ctx);
        // 3.启动服务
        server.start();
        logger.info("Start successfully!");
    }

    public static void main(String[] args) {
        try {
            // 启用web服务
            new JettyServer().start(args);
        } catch (Exception e) {
            logger.error(e.getClass() + " >> " + e.getLocalizedMessage());
        }
    }

}